import os
from PIL import Image

dataset_dir = 'data/test/images'
result_dir = 'data/test/grey_images'

if not os.path.exists(result_dir):
    os.makedirs(result_dir)

# 遍历数据集目录
for root, dirs, files in os.walk(dataset_dir):
    for file in files:
        # 检查文件是否为TIF格式
        if file.endswith('.tif'):
            # 构建完整的文件路径
            file_path = os.path.join(root, file)
            # 打开图像
            img = Image.open(file_path)
            # 转换为灰度图
            gray_img = img.convert('L')
            # 构建新的文件名和路径
            rel_path = os.path.relpath(root, dataset_dir)
            new_dir = os.path.join(result_dir, rel_path)
            if not os.path.exists(new_dir):
                os.makedirs(new_dir)
            new_file_path = os.path.join(new_dir, os.path.splitext(file)[0] + '_gray.png')
            # 保存灰度图
            gray_img.save(new_file_path, 'PNG')
            print(f'Converted {file} to {os.path.basename(new_file_path)}')

print("All TIF files have been converted to grayscale PNG and saved in the grey_images directory.")